package com.xywy.wjk.fragment;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.xywy.R;
import com.xywy.common.bean.ConnectedDevice;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.ble.util.BleTemperatureProvider;
import com.xywy.wjk.util.WjkConstant;
import com.xywy.wjk.widget.CircularSeekBar;
import com.xywy.wjk.widget.TipDialog;
import com.xywy.wjk.widget.CircularSeekBar.OnSeekChangeListener;
import com.xywy.wjk.widget.TemperatureView;

/**
 * 体温fragment
 * @author wwl
 *
 */
public class TempperatureFragment extends Fragment implements OnClickListener {
	private Button btn_start;
	private LinearLayout ll_not_connectted_prompot;
	private boolean tempture_connect_status = false; //连接状态
	private BleTemperatureProvider utils;
	private BluetoothAdapter.LeScanCallback mLeScanCallback;
	private BluetoothAdapter mBluetoothAdapter ;
	private BluetoothDevice mBluetoothDevice;
	private boolean mScanning;
	private boolean flag = false; //连接判断控制次数
	private TemperatureView tempeture_view;
	CircularSeekBar circular_view;
	
	TipDialog dialog;
	
	private void scanLeDevice(final boolean enable) {

		// 扫描到的蓝牙设备的响应设置
		// http://www.tuicool.com/articles/yU3y63n
		mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

			@Override
			public void onLeScan(final BluetoothDevice device, int rssi,
					byte[] scanRecord) {
				// TODO Auto-generated method stub
				String Thermometer = "DoouYa Thermometer";
				// DoouYa Thermometer
				System.out.println(">>>>>>>>>>onLeScan " + device.getName());
				if (device.getName().contains(Thermometer)) {
					System.out.println(">>>>>>>>>>Find Sphygmomanometer");
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					mBluetoothDevice = device;
					mBluetoothAdapter.stopLeScan(mLeScanCallback);
					if(flag){
					}else {
						flag = true;
					
						getActivity().runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								utils.connectTemputer(getActivity(), mBluetoothDevice);
							}
						});
					}
				}

			}
		};

		if (enable) {
			System.out.println(">>>>>>>>>>Begain mHandler");
			mScanning = true;
			mBluetoothAdapter.startLeScan(mLeScanCallback);
		} else {
			mScanning = false;
			mBluetoothAdapter.stopLeScan(mLeScanCallback);
		}
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initReceiver();
		utils = BleTemperatureProvider.getInstance(getActivity());
		mBluetoothAdapter = utils.getAdaper();
	}
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    		Bundle savedInstanceState) {
    	View view = View.inflate(getActivity(), R.layout.wjk_temperature_fragment, null);
         initView(view);
    	return view;
    }
    
    private void initView(View v){
    	btn_start = (Button) v.findViewById(R.id.btn_start);
    	ll_not_connectted_prompot = (LinearLayout) v.findViewById(R.id.ll_not_connectted_prompot);
    	tempeture_view = (TemperatureView) v.findViewById(R.id.tempeture_view);
    	ll_not_connectted_prompot.setOnClickListener(this);
    	circular_view = (CircularSeekBar) v.findViewById(R.id.circular_view);
    	btn_start.setOnClickListener(this);
    	btn_start.setEnabled(false);
    	
    	circular_view.setMaxProgress(100);
        circular_view.setProgress(70);

        circular_view.setSeekBarChangeListener(new OnSeekChangeListener() {

            @Override
            public void onProgressChange(CircularSeekBar view, int newProgress) {
                Log.d("Welcome", "Progress:" + view.getProgress() + "/" + view.getMaxProgress());
            }
        });

    }
    
    //注册广播
    private void initReceiver(){
    	getActivity().registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    	IntentFilter filter = new IntentFilter(WjkConstant.CONNECTING_TEMPUT_ACTION);
    	getActivity().registerReceiver(new ChangeReceiver(), filter);
    }
    
    
	/**
	 * 广播过滤器 蓝牙状态的处理
	 * 
	 * @return
	 */
	private static IntentFilter makeGattUpdateIntentFilter() {
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(BleTemperatureProvider.ACTION_GATT_CONNECTED);
		intentFilter.addAction(BleTemperatureProvider.ACTION_GATT_DISCONNECTED);
		intentFilter.addAction(BleTemperatureProvider.ACTION_GATT_SERVICES_DISCOVERED);
		intentFilter.addAction(BleTemperatureProvider.ACTION_DATA_AVAILABLE);
		intentFilter.addAction(BleTemperatureProvider.ACTION_READ_CHARACTERISTIC);
		intentFilter.addAction(BleTemperatureProvider.ACTION_SYSTEMID);
		intentFilter.addAction(BleTemperatureProvider.ACTION_XUEYA_DATA);
		intentFilter.addAction(BleTemperatureProvider.ACTION_WEIGHT_DATA);
		intentFilter.addAction(BleTemperatureProvider.ACTION_WRITE_DATA_AVAILABLE);
		return intentFilter;

	}
    /*
	 * 和蓝牙设备进行交互的广播
	 */
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BleTemperatureProvider.ACTION_GATT_CONNECTED.equals(action)) {
				stateSuc();
			} else if (BleTemperatureProvider.ACTION_GATT_DISCONNECTED.equals(action)) {// 断开连接时
			    stateFailed();
			} else if (BleTemperatureProvider.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
				/* 可以获取所有的通道 */
				
			} else if (BleTemperatureProvider.ACTION_WRITE_DATA_AVAILABLE.equals(action)) {
				
			} else if (BleTemperatureProvider.ACTION_DATA_AVAILABLE.equals(action)) {

			}else if (BleTemperatureProvider.ACTION_WEIGHT_DATA.equals(action)) {
				btn_start.setEnabled(true);
			}else if (BleTemperatureProvider.ACTION_XUEYA_DATA.equals(action)) {
				final String TempratureData = intent.getStringExtra("TempratureData");
				getActivity().runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						if(TempratureData != null){
							float tem = Float.parseFloat(TempratureData);
							Log.e("aaa", tem+"   --------------");
							tempeture_view.setTemperature_value(tem);
						}
					}
				});
			}
		}};
		
   /**
    * 连接成功
    */
		
    private void stateSuc(){
    	if(dialog !=null){
    		dialog.dismiss();
    	}
    	ConnectedDevice temp_device = FileUtil.getTemputerDevice();
    	temp_device.setConnect_time(System.currentTimeMillis());
    	temp_device.setConnected(true);
    	FileUtil.saveTemputerDevice(temp_device);
    	hideLine();
    	tempture_connect_status = true;
    }
    /**
     * 连接失败
     */
    
    private void stateFailed(){
    	showLine();
    	ConnectedDevice temp_device = FileUtil.getTemputerDevice();
    	temp_device.setConnected(false);
    	FileUtil.saveTemputerDevice(temp_device);
    	btn_start.setEnabled(false);
    	tempture_connect_status = false;
    }
	private void hideLine(){
		ll_not_connectted_prompot.setVisibility(View.GONE);
	}
	
	private void showLine(){
		ll_not_connectted_prompot.setVisibility(View.VISIBLE);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_start:
			utils.startTest();
		    btn_start.setText("正在测量请稍后");
		    btn_start.setEnabled(false);
			break;
		case R.id.ll_not_connectted_prompot:
			flag = false;
			showScaningDialog();
			scanLeDevice(true);
			break;
		default:
			break;
		}
	}
	
	
	class ChangeReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(WjkConstant.CONNECTING_TEMPUT_ACTION.equals(action)){
				System.out.println("现在开始体温的蓝牙连接----2222222");
				flag = false;
				showScaningDialog();
				scanLeDevice(true);
			}
		}
	}
	
	Handler blueToothHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case TipDialog.DIALOG_TIMER_CANCLE:
				stateFailed();
				break;

			default:
				break;
			}
		};
	};
	
	private void showScaningDialog(){
		if(dialog == null){
			dialog = new TipDialog(getActivity(), TipDialog.VIEW_LOADING, blueToothHandler);
		}
		dialog.show();
	}
}
